import {
	defineStore
} from 'pinia';
import app from './app';

const permission = defineStore({
	id: 'permission',
	state: () => ({
		boxshow: false, //弹窗
		show: false, // 显示动画
		permissionList: [], // 被拒绝的权限  临时拒绝的不会加入进来
		// 成功回调函数
		success: null,
		// 失败回调函数
		fail: null,
		permissionID: '', // 逗号分隔的字符串 WRITE_EXTERNAL_STORAGE,CAMERA
		openShow:true // 是否显示去开启权限弹窗
	}),
	getters: {},
	actions: {
		// 请求权限
		requestPermissions() {
			// 辅助函数：准备 Android 权限字符串
			const prepareAndroidPermissions = (permissions) => {
				return permissions.map(permission => `android.permission.${permission}`);
			};

			const handleAndroidPermissions = () => {
				this.boxshow = true
				const permissions = this.permissionID.split(',');
				const permissionIDs = prepareAndroidPermissions(permissions);
				Promise.all(permissions.map(permission => this.getcheckPermission(permission)))
					.then(results => {
						// 当前的权限被拒绝
						// 第一次请求权限的时候 默认都是-1 且 permissionList 是空数组 一定会显示
						// 第二次 请求权限的时候 就需要判断 permissionList 里面是否有 当前申请权限 如果有的话 就说明 第一次请求的时候给拒绝了 这样就第二次就不用显示这个提示了
						// 用户第二次手动去开启权限的话 第三次请求的时候默认也是不显示 然后 走了已授权的判断之后自动删除了 permissionList 存在的权限数据 这样第四次就可以重头开始判断
						if (results.some(result => result.checkResult == -1)) {
							if (permissions.length === 1 && !this.permissionList.includes(permissions[0])) {
								this.show = true
							}
							// 如果是两个权限的话 需要判断 其中只要有一个在就不弹窗
							if (permissions.length > 1 && (!this.permissionList.includes(permissions[0]) && !this.permissionList.includes(permissions[1]))) {
								this.show = true
							}
						}
					})
					.catch(err => {
						console.error(err);
					});



				plus.android.requestPermissions([...permissionIDs], e => {
					// 关闭权限申请目的自定义弹框
					this.show = false;
					this.boxshow = false;
					//已授权
					if (e.granted.length > 0) {
						// 两个权限的话 必须要都同意才能走成功回调
						if (permissions.length > 1 && e.granted.length > 1) {
							this.deletePermission(permissions)
							this.success && this.success()
						}
						if (permissions.length === 1) {
							this.deletePermission(permissions)
							this.success && this.success()
						}
					}
					// 临时拒绝
					if (e.deniedPresent.length > 0) {
						this.fail && this.fail()
					}
					// 已被永久禁用
					if (e.deniedAlways.length > 0) {
						let lists = e.deniedAlways.map(item => {
							return item.split('android.permission.')[1]
						})
						this.setPermission(lists)
						this.fail && this.fail()
						this.openShow && this.openSetting()
					}
				});
			}


			if (plus.os.name === 'Android') {
				handleAndroidPermissions()
			} else {
				this.success && this.success()
			}

		},
		// 检测当前的权限是否开启
		getcheckPermission(id) {
			return new Promise((resolve, reject) => {
				plus.android.checkPermission('android.permission.' + id,
					granted => {
						resolve({
							type: id,
							checkResult: granted.checkResult
						})
					},
					error => {
						reject()
					}
				);
			})
		},
		// 设置权限
		setPermission(data) {
			data.map(item => {
				if (!this.permissionList.includes(item)) {
					this.permissionList.push(item)
				}
			})
		},
		// 删除被禁用列表里面存在的权限
		deletePermission(data) {
			let indexList = data.map(item => {
				let i = this.permissionList.findIndex(value => value === item)
				return i
			})
			indexList.map(item => {
				this.permissionList.splice(item, 1)
			})
		},
		openSetting() {
			uni.showModal({
				title: '温馨提示',
				content: '还没有该权限，立即去设置开启？',
				cancelText: "取消",
				confirmText: "去设置",
				showCancel: true,
				confirmColor: '#000',
				cancelColor: '#666',
				success: (res) => {
					if (res.confirm) {
						this.goSetting();
					}
				},
				fail: () => {}
			})
		},
		goSetting() {
			if (plus.os.name == "iOS") {
				var UIApplication = plus.ios.import("UIApplication");
				var application2 = UIApplication.sharedApplication();
				var NSURL2 = plus.ios.import("NSURL");
				var setting2 = NSURL2.URLWithString("app-settings:");
				application2.openURL(setting2);
				plus.ios.deleteObject(setting2);
				plus.ios.deleteObject(NSURL2);
				plus.ios.deleteObject(application2);
			} else {
				var Intent = plus.android.importClass("android.content.Intent");
				var Settings = plus.android.importClass("android.provider.Settings");
				var Uri = plus.android.importClass("android.net.Uri");
				var mainActivity = plus.android.runtimeMainActivity();
				var intent = new Intent();
				intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
				var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
				intent.setData(uri);
				mainActivity.startActivity(intent);
			}
		},
	},
	persist: {
		enabled: true,
		strategies: [{
			key: 'permission-store',
		}, ],
	},
});

export default permission;